package com.laxcen.facestaticcheck.util;

import android.graphics.Bitmap;

import com.laxcen.facestaticcheck.Const;

import org.opencv.android.Utils;
import org.opencv.core.Core;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.core.MatOfDouble;
import org.opencv.core.MatOfFloat;
import org.opencv.core.MatOfInt;
import org.opencv.core.MatOfRect;
import org.opencv.core.Rect;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;
import org.opencv.objdetect.CascadeClassifier;

import java.util.Arrays;
import java.util.List;


public class OpenCVUtil {
    private static float threshold = Const.FACE_IMAGE_DEFINITION;
    private static Result doDetect(Mat image) {
        Mat gray = new Mat();
        Imgproc.cvtColor(image,gray,Imgproc.COLOR_BGR2GRAY);
        Mat laplaci = new Mat();
        Imgproc.Laplacian(gray, laplaci, CvType.CV_64F);
        MatOfDouble means = new MatOfDouble();
        MatOfDouble stddev = new MatOfDouble();
        Core.meanStdDev(laplaci, means, stddev);
        List<Double> meansIndexer = means.toList();
        List<Double> stddevIndexer = stddev.toList();
        double men = meansIndexer.get(0);
        double dev = stddevIndexer.get(0);
        return new Result(threshold, (float) dev, dev < threshold);
    }

    public static Result detect(Bitmap bitmap) {
        Mat image =new Mat();
        Utils.bitmapToMat(bitmap,image);
        return doDetect(image);
    }


    /**
     * 人脸对比
     * @param img_1
     * @param img_2
     * @return
     */
    public static double compareFace(Bitmap img_1, Bitmap img_2){
        Mat mat_1 = new Mat();
        Mat mat_2 = new Mat();
        Utils.bitmapToMat(img_1,mat_1);
        Utils.bitmapToMat(img_2,mat_2);

        Mat hist_1 = new Mat();
        Mat hist_2 = new Mat();
        MatOfFloat ranges = new MatOfFloat(0f, 256f);
        MatOfInt histSize = new MatOfInt(10000000);
        Imgproc.calcHist(Arrays.asList(mat_1), new MatOfInt(0), new Mat(), hist_1, histSize, ranges);
        Imgproc.calcHist(Arrays.asList(mat_2), new MatOfInt(0), new Mat(), hist_2, histSize, ranges);
        double res = Imgproc.compareHist(hist_1, hist_2, Imgproc.CV_COMP_CORREL);
        return res;
    }


    public static class Result {
        private final float threshold;
        private final float result;
        private final boolean hasError;

        Result(float threshold, float result, boolean hasError) {
            this.threshold = threshold;
            this.result = result;
            this.hasError = hasError;
        }

        public boolean isHasError() {
            return hasError;
        }

        public float getThreshold() {
            return threshold;
        }

        public float getResult() {
            return result;
        }
    }
}
